package sshDesktop

// AddWebsocket 添加 websocket 连接
func (deskssh *DesktopSSH) HandleShell(key string) {
	var inputChan = make(chan string)
	var outputChan = make(chan string)
	DesktopSSHInputMap[key] = inputChan
	DesktopSSHOutputMap[key] = outputChan
	deskssh.logger.Printf("%d:%s连接成功", deskssh.UserID, deskssh.ClientName)
	go deskssh.ExecuteShell(key)
}

func (deskssh *DesktopSSH) ExecuteShell(key string) {
	defer func() {
		deskssh.logger.Printf("%d:%s关闭客户端成功", deskssh.UserID, deskssh.ClientName)
		deskssh.Client.Close()
	}()

	for {
		select {
		case data := <-DesktopSSHInputMap[key]:
			if data == "exit" {
				DesktopSSHOutputMap[key] <- "客户端关闭成功"
				close(DesktopSSHInputMap[key])
				close(DesktopSSHOutputMap[key])
				delete(DesktopSSHInputMap, key)
				delete(DesktopSSHOutputMap, key)
				return
			}

			deskssh.logger.Printf("desktop command: %s", data)
			session, err := deskssh.Client.NewSession()
			if err != nil {
				panic(err)
			}
			res, err := session.CombinedOutput(data)
			if err != nil {
				deskssh.logger.Printf("shll执行失败")
				DesktopSSHOutputMap[key] <- ""
			} else {
				DesktopSSHOutputMap[key] <- string(res)
			}
		}
	}
}
